﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using LuckyBingoRcon.Commands.Events;

namespace LuckyBingoRcon.Commands
{
	public class ServernameCommand : Command
	{
		public EventHandler<ServernameCommandEventArgs> OnResponse;
        
        public ServernameCommand()
        {
            base.commandText = "sv_hostname ";
            base.args = null;
        }

		protected override void CommandOnResponse(string response)
		{
			string serverName = null;
			StringReader sr = new StringReader(response);

			try
			{
				
				while (sr.Peek() > 0)
				{
					string ln = sr.ReadLine().Trim();
					if (!String.IsNullOrEmpty(ln) && (ln.StartsWith("\"sv_hostname") || ln.StartsWith("sv_hostname")))            // Heli: Server name line has "sv_hostname", not sv_hostname at beginning
					{
						int index = ln.IndexOf("is:");                                          // Heli: Find (if packet was received correctly) the server name start index
						if (index > 0 && index < ln.Length - 5)
						{
							ln = ln.Remove(0, index + 5);                                       // Remove all characters before server name ...
							index = ln.IndexOf("default");
							if (index > 4)
								ln = ln.Remove(index - 4);
							serverName = ln.Trim();
							break;
						}
					}
				}


				if (OnResponse != null)
				{
					ServernameCommandEventArgs e = new ServernameCommandEventArgs();
					e.ServerName = serverName;
					OnResponse(this, e);
				}
			}
			catch (Exception error)
			{
				if (OnResponse != null)
				{
					ServernameCommandEventArgs e = new ServernameCommandEventArgs();
					e.ServerName = serverName;
					e.Error = error;
					OnResponse(this, e);
				}
			}

			sr.Close();
		}

        public override string ToString()
        {
            return "Get\tServer Name";
        }
	}
}
